package com.pactera.jep.service.sys.security.spring.conf;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.core.code.LogType;
import com.pactera.jep.core.code.OperateType;
import com.pactera.jep.core.entity.Log;
import com.pactera.jep.core.service.LogService;
import com.pactera.jep.core.spring.AutoLog;
import com.pactera.jep.core.utils.IPUtils;
import com.pactera.jep.service.sys.model.DeviceLogin;
import com.pactera.jep.service.sys.security.spring.bean.UserEntity;
import com.pactera.jep.service.sys.service.DeviceLoginService;
import com.pactera.jep.service.sys.util.LogExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class WebAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private LogService logService;

    @Resource
    private DeviceLoginService deviceLoginService;

    @Override
    @AutoLog(value = "用户登录成功", logType = LogType.LOGIN, operateType = OperateType.LOGIN)
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        UserEntity user = (UserEntity) authentication.getPrincipal();
        logger.info("获取到用户数据：" + user.toString());
        response.setContentType("application/json;charset=utf-8");
        DeviceLogin deviceLogin = new DeviceLogin();
        deviceLogin.setStaffCode(user.getUserId());
        deviceLogin.setStaffName(user.getUsername());
        deviceLogin.setIp(IPUtils.getIpAddr(request));
        deviceLoginService.increase(deviceLogin);

        //保存日志
        LogExecutor.submit(() -> {
            loginLog(user, request);
        });
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        result.put("success", true);
        result.put("token", user.getToken());
        result.put("user", user.getStaff());
        result.put("menus", user.getMenus());
        result.put("userName", user.getUsername());
        result.put("roles", user.getRoles());
        out.write(result.toJSONString());
        out.flush();
        out.close();
    }

    /**
     * 记录登录日志
     *
     * @param user
     * @param request
     */
    private void loginLog(UserEntity user, HttpServletRequest request) {
        Log log = new Log();
        log.setStaffName(user.getUsername());
        log.setStaffCode(user.getUserId());
        log.setLogType(LogType.LOGIN.getValue());
        log.setOperateType(OperateType.LOGIN.getValue());
        log.setUrl("/doLogin");
        log.setOperateDesc("用户登录成功");
        log.setIp(IPUtils.getIpAddr(request));
        log.setMacAddress(log.getIp());
        try {

            long startTime = (Long) request.getAttribute("startTime");
            request.removeAttribute("startTime");
            long endTime = System.currentTimeMillis();
            log.setCostTime(String.valueOf(endTime - startTime));
        } catch (Exception e) {
            log.setCostTime("0");
        }
        logService.addLog(log);

    }
}
